'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { contentId, type, adminId } = event;

  if (!contentId || !type) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  try {
    const contentCollection = db.collection('add-content');
    
    // 先获取内容信息用于日志记录
    const contentResult = await contentCollection.doc(contentId).get();
    if (!contentResult.data || contentResult.data.length === 0) {
      return {
        code: 404,
        msg: '内容不存在',
        data: null
      };
    }

    const content = contentResult.data[0];

    // 删除内容
    const deleteResult = await contentCollection.doc(contentId).remove();

    // 记录删除日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: type,
      target_id: contentId,
      action: 'deleted',
      admin_id: adminId || 'admin',
      content_info: {
        title: content.title || '',
        content: content.content,
        user_id: content.user_id,
        category: content.category
      },
      create_time: new Date()
    });

    // 如果是活动，需要处理参与者相关数据
    if (type === 'activity') {
      try {
        const participantCollection = db.collection('activity_participants');
        await participantCollection.where({
          activity_id: contentId
        }).update({
          activity_deleted: true,
          delete_time: new Date()
        });
      } catch (participantError) {
        console.log('更新活动参与者记录失败:', participantError);
      }
    }

    // 如果是帖子，需要处理评论和点赞相关数据
    if (type === 'post') {
      try {
        const commentCollection = db.collection('user-comment');
        await commentCollection.where({
          post_id: contentId
        }).update({
          post_deleted: true,
          delete_time: new Date()
        });

        const likeCollection = db.collection('user-likes');
        await likeCollection.where({
          post_id: contentId
        }).update({
          post_deleted: true,
          delete_time: new Date()
        });
      } catch (relatedError) {
        console.log('更新相关记录失败:', relatedError);
      }
    }

    return {
      code: 200,
      msg: '内容删除成功',
      data: {
        contentId: contentId,
        type: type,
        deleted: deleteResult.deleted
      }
    };
  } catch (error) {
    console.error('删除内容失败:', error);
    return {
      code: 500,
      msg: '删除内容失败',
      data: null
    };
  }
};
